﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;

namespace WeatherUSB
{
    public static class LoadData
    {
        private const int DATALENGTH = 784;

        [DllImport(@"HID_DLL.dll")]
        static extern unsafe bool InitCommunication();

        [DllImport(@"HID_DLL.dll")]
        static extern unsafe bool CommIO(bool Flag);

        [DllImport(@"HID_DLL.dll")]
        static extern unsafe bool WriteData(byte[] WriteBuffer, int BufferLength);

        [DllImport(@"HID_DLL.dll")]
        static extern unsafe bool ReadData(byte[] ReadBuffer, int BufferLength);

        [DllImport(@"HID_DLL.dll")]
        static extern unsafe bool USBQuit();


        public static string OpenUSB()
        {
            bool b = InitCommunication();
            if (b == false)
            {
                return
                     "Error. Please make sure breast mate unit is properly connected to the computer";
            }
            return string.Empty;
        }

        public static string CloseUSB()
        {
            try
            {
                bool b = USBQuit();
            }
            catch
            {
            }
            return string.Empty;
        }

        public static byte[] DownUSB()
        {
            bool b;
            //bool b = InitCommunication();
            //if (b == false)
            //{
            //    return
            //         "Error. Please make sure breast mate unit is properly connected to the computer";
            //}

            byte[] data = new byte[DATALENGTH];

            b = ReadData(data, DATALENGTH);
            if (b == false)
            {
                return null;
            }

            return data;
            //for (int i = 0; i < data.Length; i++)
            //{
            //    data[i] = 0xff;
            //}

            //b = WriteData(data, data.Length);
            //if (b == false)
            //{
            //    return
            //         "Error. Please make sure breast mate unit is properly connected to the computer";
            //}

            //return string.Empty;
        }

        public static string DeleteAllData()
        {
            byte[] data = new byte[DATALENGTH];
            for (int i = 0; i < data.Length; i++)
            {
                data[i] = 0xff;
            }

            bool b = WriteData(data, data.Length);
            if (b == false)
            {
                return
                     "Error. Please make sure breast mate unit is properly connected to the computer";
            }

            return string.Empty;
        }
    }
}

